<template>
  <view class="container">
    <!--input列表 -->
    <view class="input-box">
      <view class="section">
        <text>收 货 人</text>
        <input
          placeholder="姓名"
          type="text"
          maxlength="15"
          :value="name"
          @input="onReceiverInput"
        >
      </view>
      <view class="section">
        <text>手机号码</text>
        <input
          placeholder="11位手机号码"
          type="number"
          maxlength="11"
          :value="phone"
          @input="onMobileInput"
        >
      </view>
      <view
        class="section"
        @tap="translate"
      >
        <text>所在地区</text>
        <view class="pca">
          {{ province }} {{ city }} {{ area }}
        </view>
        <view
          class="animation-element-wrapper"
          :animation="animation"
          :style="'visibility:' + (show ? 'visible':'hidden')"
          @tap.stop="hiddenFloatView"
        >
          <view
            class="animation-element"
            @tap.stop="nono"
          >
            <text
              class="right-bt"
              @tap.stop="hiddenFloatView"
            >
              确定
            </text>
            <view class="line" />
            <picker-view
              indicator-style="height: 50rpx;"
              :value="valArr"
              @change="bindChange"
              @tap.stop="nono"
            >
              <!--省-->
              <picker-view-column>
                <view
                  v-for="(item, indexs) in provArray"
                  :key="indexs"
                >
                  {{ item.areaName }}
                </view>
              </picker-view-column>
              <!--地级市-->
              <picker-view-column>
                <view
                  v-for="(item, indexss) in cityArray"
                  :key="indexss"
                >
                  {{ item.areaName }}
                </view>
              </picker-view-column>
              <!--区县-->
              <picker-view-column>
                <view
                  v-for="(item, indexsss) in areaArray"
                  :key="indexsss"
                >
                  {{ item.areaName }}
                </view>
              </picker-view-column>
            </picker-view>
          </view>
        </view>

        <view class="arrow">
          <image src="@/static/images/icon/more.png" />
        </view>
      </view>
      <view class="section">
        <text>详细地址</text>
        <input
          placeholder="如楼号/单元/门牌号"
          type="text"
          :value="addr"
          @input="onAddrInput"
        >
      </view>
      <view class="section">
        <text>默认地址</text>
        <view class="section-item">
          <radio-group class="radio-group" @change="onChangeRadio">
            <radio
              color="#eb2444"
              :value="1"
              :checked="yesChecked"
              style="transform:scale(0.6)"
            />是
            <radio
              color="#eb2444"
              :value="2"
              :checked="noChecked"
              style="transform:scale(0.6)"
            />否
          </radio-group>
        </view>
      </view>
    </view>
    <!-- end input列表 -->
    <!-- 协议 -->
    <view class="agreement">
      <checkbox-group class="checkbox-dot" @change="onChange">
        <checkbox class="checkbox-dot" :checked="false" value="cb" style="transform:scale(0.6)"  />
        同意已阅读<text @tap="onRead('1')">《用户服务协议》</text>和<text @tap="onRead('2')">《隐私政策》</text>
      </checkbox-group>
    </view>
    <!-- 功能按钮 -->
    <view class="btn-box">
      <view
        class="keep btn"
        @tap="onSaveAddr"
      >
        <text>保存收货地址</text>
      </view>

      <view
        v-if="addrId!=0"
        class="clear btn"
        @tap="onDeleteAddr"
      >
        <text>删除收货地址</text>
      </view>
    </view>
    <!-- end 功能按钮 -->
  </view>
</template>

<script setup>
import addressList from '@/utils/area.js'
const addrId = ref(0)
const city = ref('')
const area = ref('')
const provinceId = ref(0)
const cityId = ref(0)
const areaId = ref(0)
const name = ref('')
const phone = ref('')
const addr = ref('')
const province = ref('')
const checked = ref([])
const ifMr = ref('')
const yesChecked = ref(false)
const noChecked = ref(false)
onLoad((options) => {
  const { id, address, addressInfo } = options
  if (id) {
    addrId.value = id
    province.value = address.split(' ')[0]
    provinceId.value = filterId(province.value)
    city.value = address.split(' ')[1]
    cityId.value = filterId(city.value)
    area.value = address.split(' ')[2]
    areaId.value = filterId(area.value)
    name.value = options?.name
    phone.value = options?.phone
    addr.value = addressInfo
    ifMr.value = Number(options?.ifMr) ?? ""
    yesChecked.value = ifMr.value == 1 ? true : false
    noChecked.value = ifMr.value == 2 ? true : false
    initCityData(provinceId.value, cityId.value, areaId.value)
  } else {
    initCityData(provinceId.value, cityId.value, areaId.value)
  }
})

const provArray = ref([])
const valArr = ref([0, 0, 0])
const initCityData = (provinceId, cityId, areaId) => {
    provArray.value = addressList?.filter(m => {
      return m.level == 1
    })
    const area = provArray.value[0] ?? {}
    province.value = area.areaName
    getCityArray(area.areaId)
}
const filterId = (name) => {
  addressList?.map(m => {
    if(m.areaName == name){
      return m.areaId
    }
  })
}
let indexArr = [18, 0, 0]
const areaArray = ref([])
const cityArray = ref([])
/**
 * 滑动事件
 */
const bindChange = (e) => {
  // 判断滑动的是第几个column
  const val = e.detail.value
  // 若省份column做了滑动则定位到地级市和区县第一位
  if (indexArr[0] != val[0]) {
    val[1] = 0
    val[2] = 0 // 更新数据
    // 获取地级市数据
    getCityArray(provArray.value[val[0]].areaId)
  } else {
    // 若省份column未做滑动，地级市做了滑动则定位区县第一位
    if (indexArr[1] != val[1]) {
      val[2] = 0 // 更新数据
      getAreaArray(cityArray.value[val[1]].areaId) // 获取区县数据
    }
  }
  indexArr = val
  valArr.value = [val[0], val[1], val[2]]
  province.value = provArray.value[valArr.value[0]].areaName
  city.value = cityArray.value[valArr.value[1]].areaName
  area.value = areaArray.value[valArr.value[2]].areaName
  provinceId.value = provArray.value[valArr.value[0]].areaId
  cityId.value = cityArray.value[valArr.value[1]].areaId
  areaId.value = areaArray.value[valArr.value[2]].areaId
}

let t = 0
let moveY = 200
const show = ref('')
/**
 * 移动按钮点击事件
 */
const translate = () => {
  if (t == 0) {
    moveY = 0
    show.value = true
    t = 1
  } else {
    moveY = 200
    show.value = false
    t = 0
  }
  animationEvents(moveY, show.value)
}

/**
 * 隐藏弹窗浮层
 */
const hiddenFloatView = () => {
  moveY = 200
  show.value = false
  t = 0
  animationEvents(moveY, show.value)
}

const animation = ref('')
/**
 * 动画事件
 */
const animationEvents = (moveY, showParam) => {
  animation.value = uni.createAnimation({
    transformOrigin: '50% 50%',
    duration: 400,
    timingFunction: 'ease',
    delay: 0
  })
  animation.value.translateY(moveY + 'vh').step()
  animation.value = animation.value.export()
  show.value = showParam
}

/**
 * 根据省份ID获取 城市数据
 */
const getCityArray = (id) => {
  cityArray.value = addressList.filter((m) => {
    return m.parentId == id
  })
  const { areaId, areaName } = cityArray.value[0]  ?? {}
  city.value = areaName
  getAreaArray(areaId)
}

/**
 * 根据城市ID获取 区数据
 */
  const getAreaArray = (areaId) => {
    areaArray.value = addressList.filter((m) => {
      return m.parentId == areaId
    })
    area.value = areaArray.value[0]?.areaName
}

const onChangeRadio = (e) => {
  ifMr.value = e.detail.value
}
const onChange = (e) => {
  checked.value = e.detail.value
}
/**
 * 保存地址
 */
const onSaveAddr = () => {
  const receiverParam = name.value
  const mobileParam = phone.value
  const addrParam = addr.value

  if (!receiverParam.trim()) {
    name.value = ''
    uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    })
    return
  }

  if (!mobileParam) {
    uni.showToast({
      title: '请输入手机号码',
      icon: 'none'
    })
    return
  }

  if (mobileParam.length != 11) {
    uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    })
    return
  }

  if (!addrParam.trim()) {
    addr.value = ''
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    })
    return
  }

  if(checked.value.length == 0){
    uni.showToast({
      title: '请勾选《用户服务协议》《隐私协议》！',
      icon: 'none'
    })
    return
  }

  uni.showLoading()
  const data = {
    openId: uni.getStorageSync('openId'),
    name: name.value,
    phone: phone.value,
    address: `${province.value} ${city.value} ${area.value}`,
    addressInfo: addr.value,
    ifMr: ifMr.value
  }
  if(addrId.value){
    data.id = addrId.value
  }
  http.request({
    url: '/xcx/editUserAddress',
    method: 'POST',
    data
  }).then(() => {
    uni.hideLoading()
    uni.navigateBack({
      delta: 1
    })
  })
}
const onReceiverInput = (e) => {
  name.value = e.detail.value
}
const onMobileInput = (e) => {
  phone.value = e.detail.value
}
const onAddrInput = (e) => {
  addr.value = e.detail.value
}

/**
 * 删除配送地址
 */
const onDeleteAddr = () => {
  uni.showModal({
    title: '',
    content: '确定要删除此收货地址吗？',
    confirmColor: '#eb2444',
    success (res) {
      if (res.confirm) {
        uni.showLoading()
        http.request({
          url: '/xcx/delUserAddress',
          method: 'POST',
          data: {
            id: addrId.value
          }
        }).then(() => {
          uni.hideLoading()
          uni.navigateBack({
            delta: 1
          })
        })
      }
    }
  })
}
</script>

<style scoped lang="scss">
@use './editAddress.scss';
.agreement{
  padding: 20rpx;
  color: #333;
  font-size: 28rpx;
  text{
    color: #fc0130;
  }
}
</style>
